#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>

#include "BinaryTree.h"

using namespace std;

namespace BinaryTreeSp {

BinaryTree::BinaryTree(int (*cmp)(void *data1, void *data2))
{
    root = NULL;
    num = 0;
    compare = cmp;
}

BinaryTree::~BinaryTree()
{
    
}

TreeNode * BinaryTree::getLeftNode(TreeNode *root)
{
    return root == NULL ? NULL : root->left;
}

TreeNode * BinaryTree::getRightNode(TreeNode *root)
{
    return root == NULL ? NULL : root->right;
}

void * BinaryTree::getData(TreeNode *root)
{
    return root == NULL ? NULL : root->data;
}

TreeNode *BinaryTree::getRoot(void)
{
    return root;
}

void BinaryTree::insertNode(TreeNode *root, TreeNode *node)
{
    if(compare(node->data, root->data)) {
        TreeNode *rightNode = getRightNode(root);
        if(rightNode == NULL) {
            cout << "insert " << *(int *)node->data << " to right" << endl;
            root->right = node;
            return;
        } else {
            insertNode(rightNode, node);
        }
    } else {
        TreeNode *leftNode = getLeftNode(root);
        if(NULL == leftNode) {
            cout << "insert " << *(int *)node->data << " to left" << endl;
            root->left = node;
            return;
        } else {
            insertNode(leftNode, node);
        }
    }
}

int BinaryTree::addData(void *data)
{
    if(NULL != data) {
        cout << "insert data is " << *(int *)data << endl;
        TreeNode *node = new TreeNode;
        node->data = data;
        node->left = NULL;
        node->right = NULL;

        if(NULL == root) {
            root = node;
        } else {
            insertNode(root, node);
        }
        num++;
    } else {
        return -1;
    }
}

int BinaryTree::deleteData(void *data)
{

}

int BinaryTree::preOrderTraverse(TreeNode *root)
{
    if(NULL != root) {
        cout << *(int *)root->data << " ";
        preOrderTraverse(getLeftNode(root));
        preOrderTraverse(getRightNode(root));
    }
}

int BinaryTree::inOrderTraverse(TreeNode *root)
{
    if(NULL != root) {
        inOrderTraverse(getLeftNode(root));
        cout << *(int *)root->data << " ";
        inOrderTraverse(getRightNode(root));
    }
}

int BinaryTree::postOrderTraverse(TreeNode *root)
{
    if(NULL != root) {
        postOrderTraverse(getLeftNode(root));
        postOrderTraverse(getRightNode(root));
        cout << *(int *)root->data << " ";
    }
}

}

